package com.sakura.demo.auth.config;

import com.sakura.demo.auth.jwt.JwtTokenEnhancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: Nelsoncan
 * @Date: 2022/5/12
 * @Description: web安全配置类
 * @Version: 1.0.0 创建
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class SakuraWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 特别注意：使用授权码方式进行获取授权码时要求用户必须登录，如果这时用户没有登录，则需要跳转到登录页面，可自定义登录页面
        // 在antMatchers里配置放行该路径是没有作用的
        // 请求格式：http://localhost:9002/oauth/authorize?client_id=sakura-app&redirect_uri=http://localhost:8848/nacos&response_type=code&scope=all
        // AuthorizationEndpoint类中有验证用户的登录信息
        http.formLogin();

        http.authorizeRequests()
                // 放行所有actuator的请求
                .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
                // 放行获取公钥接口
                .antMatchers("/rsa/publicKey", "/user/logout").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
